package com.bawei.ngpsdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class BaiduActivity extends AppCompatActivity {

    private MyLocationListener mLocationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLocationListener = new MyLocationListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationListener.startLocation(); // 开始定位
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationListener.stopLocation(); // 停止定位
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        private LocationClient mLocationClient;

        public MyLocationListener(Context context) {
            mLocationClient = new LocationClient(context);
            mLocationClient.registerLocationListener(this);

            LocationClientOption option = new LocationClientOption();
            option.setCoorType("bd09ll"); // 设置返回经纬度坐标类型
            option.setIsNeedAddress(true); // 设置是否需要获取地址信息
            mLocationClient.setLocOption(option);
        }

        public void startLocation() {
            mLocationClient.start(); // 开始定位
        }

        public void stopLocation() {
            mLocationClient.stop(); // 停止定位
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }

            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String address = location.getAddrStr();

            // 处理位置信息
            Toast.makeText(BaiduActivity.this, "address:"+address+"latitude:"+latitude+"longitude:"+longitude, Toast.LENGTH_SHORT).show();
        }
    }
}